package com.interview.controller;

import com.interview.entity.User;
import com.interview.entity.param.LoginParam;
import com.interview.result.Result;
import com.interview.result.ResultCode;
import com.interview.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author JiangYingbo
 */
@Tag(name = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result test(@RequestBody LoginParam loginParam,
                       HttpServletRequest req) {
        User user = userService.login(loginParam);
        HttpSession session = req.getSession();
        session.setAttribute("userId", user.getUserId());
        return new Result(ResultCode.SUCCESS, "登录成功！");
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/userInfo")
    public Result userInfo(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return new Result(401, "请求失败", "请先登录！");
        }
        return new Result(ResultCode.SUCCESS, userService.userInfo(userId));
    }

    @Operation(summary = "用户登出")
    @GetMapping("/logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("userId");
        return new Result(ResultCode.SUCCESS, "退出登录成功！");
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result register(@RequestBody User user,
                           HttpServletRequest req) {
        userService.register(user);
        HttpSession session = req.getSession();
        session.setAttribute("userId", user.getUserId());
        return new Result(ResultCode.SUCCESS, "注册成功！");
    }

    @Operation(summary = "编辑用户信息")
    @PostMapping("/editUserInfo")
    public Result editUserInfo(@RequestBody User user,
                               HttpServletRequest req) {
        HttpSession session = req.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return new Result(401, "请求失败", "请先登录！");
        }
        user.setUserId(userId);
        int i = userService.updateUserInfo(user);
        if(i <= 0){
            return new Result(ResultCode.FAILED, "修改失败！");
        }else {
            return new Result(ResultCode.SUCCESS, "修改成功！");
        }

    }

}
